<style lang="scss" scoped>
@import './login.scss';
</style>
<template>
  <view class="content">
    <u-navbar :background="navbar.background" :border-bottom="false"
              :is-back="false" :title="$t('登录')" :title-color="navbar.color">
      <view slot="right">
        <u-icon :color="navbar.color" name="more-dot-fill" style="margin-right: 20rpx;" @click="customBack">
        </u-icon>
      </view>
    </u-navbar>
    <image :src="app.logo" class="logo"></image>
    <u-form ref="uForm" :model="form" label-width="160">
      <u-form-item :label="$t('手机号')" left-icon="phone-fill" prop="loginName">
        <u-input v-model="form.loginName"/>
      </u-form-item>
      <u-form-item :label="$t('密码')" left-icon="lock-fill" prop="password">
        <u-input v-model="form.password" type="password"/>
      </u-form-item>
    </u-form>
    <view class="more">
      <navigator url="../companyCode/companyCode?from=注册">
        <text>{{$t('注册')}}</text>
      </navigator>
      <navigator url="../findPassword/findPassword">
        <text>{{$t('忘记密码')}}？</text>
      </navigator>
    </view>
    <u-button :custom-style="customStyle" :loading="loading" :ripple="true" ripple-bg-color="#55aaff" shape="circle"
              type="success"
              @click="bindLogin()">
      {{$t('登录')}}
    </u-button>

    <view style="display: flex;align-items: center;margin-top: 20px;">
      <u-checkbox-group>
        <u-checkbox v-model="user_agreement">{{$t('登陆即代表阅读并同意')}}</u-checkbox>
      </u-checkbox-group>
      <navigator style="display: inline-block;color: #09BB07;" url="../agreement/agreement">
        <text>{{$t('用户隐私声明')}}</text>
      </navigator>
    </view>
    <u-no-network></u-no-network>
  </view>
</template>

<script>
import permision from "@/common/permission.js"
import { requestAndroidPermission } from '@/uni_modules/x-perm-apply-instr/js_sdk/index.js'

import {
  mapGetters,
  mapActions
} from 'vuex';

export default {
  data() {
    return {
      navbar: {
        color: "#fff",
        background: {
          backgroundColor: '#0079FF'
        }
      },
      loading: false,
      customStyle: {
        background: 'linear-gradient(to right, #00aaff 0%,#0079FF 100%)',
        'margin': '80rpx 0 20rpx'
      },
      form: {
        loginName: '',
        password: '',
        cid: '', //个推
        companyId: '', //组织id
      },
      rules: {
        loginName: [{
          required: true,
          message: '请输入手机号',
          trigger: ['blur'],
        }, {
          validator: (rule, value, callback) => {
            return this.$u.test.mobile(value);
          },
          message: '手机号码不正确',
          trigger: ['blur'],
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: ['blur']
        }]
      },
      user_agreement: false, //用户协议
      ServerIp: '', //获取服务器IP
    };
  },
  components: {},
  computed: mapGetters(['userInfo', 'api', 'app']),
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad() {
    this.$nextTick(() => {
      //获取个推
      this.getui();
      //aes密码解密
      this.getStoragePassword()
    })

  },
  onShow() {
    //获取服务器IP
    this.getServerIp()
  },
  methods: {
    ...mapActions(['set_userInfo', 'set_userToken']),
    //扫码
    // async customBack() {
    //   // #ifdef APP-PLUS
    //   let status = await this.checkPermission();
    //   if (status !== 1) {
    //     return;
    //   }
    //   setTimeout(() => {
    //     this.scan()
    //   }, 1000)
    //   // #endif
    // },
    // async checkPermission(code) {
    //   let status = permision.isIOS ? await permision.requestIOS('camera') :
    //       await permision.requestAndroid('android.permission.CAMERA');

    //   if (status === null || status === 1) {
    //     status = 1;
    //   } else {
    //     uni.showModal({
    //       content: this.$t('需要相机权限'),
    //       confirmText: this.$t('设置'),
    //       success: (res) => {
    //         if (res.confirm) {
    //           permision.gotoAppSetting();
    //         }
    //       }
    //     })
    //   }
    //   return status;
    // },
    //扫码
    customBack() {
			requestAndroidPermission(['android.permission.CAMERA','android.permission.READ_EXTERNAL_STORAGE'], {
			    title: '相机/相册读取权限申请说明',
			    content: '为了识别二维码信息及相册图片,我们需要申请您设备的相机和存储权限。'
			}).then(status => {
				if(status === 1){
					uni.scanCode({
						success: (res) => {
							try {
								let url = decodeURIComponent(res.result)
								let data = JSON.parse(url)
								if (data && data.cmd === 'yunxi') {
									//判断格式
									uni.setStorage({
										key: "baseUrl",
										data: data.host,
										success: () => {
											//console.log(data.host);
											let reg = new RegExp('/stamper/apis', 'g')//g代表全部
											let newMsg = data.host.replace(reg, '/');
											//console.log(newMsg);
											uni.showToast({
												title: this.$t('扫码成功，请登录'),
												icon: 'none'
											});
											this.loading = false
											this.$u.http.setConfig({
												baseUrl: data.host,
												header: {
													'content-type': 'application/x-www-form-urlencoded',
													'us': 'app',
													'Yx-Origin': newMsg
												}
											});
										}
									})

								} else {
									uni.showToast({
										title: this.$t('无效二维码'),
										icon: 'none'
									});
								}
							} catch (e) {
								//TODO handle the exception
								uni.showToast({
									title: this.$t('无效二维码'),
									icon: 'none'
								});
							}
						}
					});
				}
			})
    },
    stringToHex(str) {
      var val = "";
      for (var i = 0; i < str.length; i++) {
        if (val === "")
          val = str.charCodeAt(i).toString(16);
        else
          val += "," + str.charCodeAt(i).toString(16);
      }
      return val;
    },
    //获取指定手机号所在的公司列表
    getOrgsByPhone(phone) {
      this.$u.get(this.api.GLOBAL_auth_org_getOrgsByPhone, {phone}).then(res => {
        if (res.data.length === 1) {
          this.form.companyId = res.data[0].id
          this.login_l()
        } else {
          if (res.data.length === 0) {
            uni.showToast({
              icon: 'none',
              title: this.$t('手机号未注册')
            });
          } else {
            this.form.companyId = res.data[0].id
            this.login_l()
          }
        }

      }).catch((err) => {
        this.loading = false
      })
    },
    //获取服务器IP
    getServerIp() {
      uni.getStorage({
        key: 'selectServer',
        success: (res) => {
          //console.log(res.data);
          this.ServerIp = res.data
        }
      });
    },
    //登陆
    bindLogin() {
      if (!this.user_agreement) {
        uni.showToast({
          title: this.$t('请同意用户协议'),
          icon: "none"
        });
        return
      }
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.loading = true
          //获取指定手机号所在的公司列表
          this.getOrgsByPhone(this.form.loginName)
        } else {
          //console.log('验证失败');
        }
      });
    },
    login_l() {
      let req = {
        aul_value1: this.form.loginName,
        aul_value2: this.form.password,
        aul_value3: this.form.cid,
        aul_value4: this.form.companyId,
      }
      this.$u.get(this.api.GLOBAL_loginV1, req).then(res => {
        this.loading = false
        if (res.code === 200) {
          //stroe存储登陆用户信息
          this.set_userInfo(res.data);
          this.set_userToken(res.data.token)
          //密码加密存储
          this.setStoragePassword()
          setTimeout(() => {
            //获取国科量子参数
            //#ifdef APP-PLUS
            this.gkQSS(res.data.phone)
            //#endif
            uni.reLaunch({
              url: '../../tabBar/index'
            });
						this.loginSuccess(res.data)
          }, 1000);
        } else if (res.code === 510) {//密码不符合规则
          //stroe存储登陆用户信息
          this.set_userInfo(res.data);
          this.set_userToken(res.data.token)
          setTimeout(() => {
            uni.reLaunch({
              url: '../setPassword/setPassword'
            });
          }, 1000);
          //密码加密存储
          this.setStoragePassword()
        }
      }).catch((err) => {
        //console.log(err);
      })
    },
    loginSuccess(userInfo) {
      if (userInfo.appV1 === true) {
        uni.$u.get(this.api.GLOBAL_app_notice_alarm, {}).then((res) => {
          if (res.code === 200 && res.data) {
            if (res.data.unreadCount !== 0) {
              uni.setTabBarBadge({
                index: 2,
                text: '' + res.data.unreadCount
              })
            } else {
              uni.setTabBarBadge({
                index: 2
              })
            }
          }
        })
      } else {
        //请求原来接口
        uni.$u.post(this.api.GLOBAL_auth_notice_getCountByNotViewedFromLogin, {}).then((res) => {
          if (res.code === 200 && res.data) {
            uni.setTabBarBadge({
              index: 2,
              text: '' + res.data
            })
          }
        })
      }
    },
    //获取国科量子参数
    gkQSS(phone) {
      this.$u.get(this.api.GLOBAL_gkQss_initKey, {uuid: phone}).then(res => {
        if (res.data.code === '00') {
          let qss = res.data.data
          if (this.app.platform === 'ios') {
            // this.$lizhao.iosQSS.initQSS(qss.pubkey, qss.prvkey, qss.kek, qss.zmk)
          } else {
            this.$lizhao.QSS.initQSS(qss.pubkey, qss.prvkey, qss.kek, qss.zmk)
          }
        }
      }).catch(err => {
        //console.log(err);
      })
    },
    getui() {
      //获取个推的getui_info信息
      let cid = plus.push.getClientInfo().clientid;
      let platform = uni.getSystemInfoSync().platform;
      this.form.cid = platform + '_' + cid;
      // // #ifdef APP-PLUS
      // if(plus.runtime.isAgreePrivacy()||platform) {
      // 	let cid = plus.push.getClientInfo().clientid;
      // 	this.form.cid = platform + '_' + cid;
      // }else{
      //   // 运行在disagreeMode模式，不能调用限制API
      //   // 这里可以引导用户同意隐私政策
      //   plus.runtime.showPrivacyDialog(options);
      // }
      // // #endif
    },
    //密码加密存储
    setStoragePassword() {
      let password = this.$lizhao.AES.EncryptECB(this.form.password, 'password')
      let form = {
        ...this.form,
        password,
      }
      //存储用户名密码
      uni.setStorage({
        key: 'user_password',
        data: form
      });
    },
    //aes密码解密
    getStoragePassword() {
      uni.getStorage({
        key: 'user_password',
        success: (res) => {
          this.form.loginName = res.data.loginName;
          let password = this.$lizhao.AES.DecryptECB(res.data.password, 'password')
          this.form.password = password;
        }
      });
    }
  }
};
</script>
